package com.virgo.demo.system.controller.admin;

import cn.hutool.crypto.SecureUtil;
import com.virgo.common.entity.IResponse;
import com.virgo.common.utils.IValidateUtils;
import com.virgo.demo.system.domain.bo.AdminUserLoginBo;
import com.virgo.demo.system.service.AdminLoginService;
import com.virgo.limit.annotation.RepeatSubmit;
import com.virgo.redis.service.CacheService;
import com.virgo.web.utils.IRequestUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController
@RequestMapping("/manage168/login")
@RequiredArgsConstructor
public class AdminLoginController {

	private final AdminLoginService adminLoginService;

    private final CacheService cacheService;

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@RepeatSubmit
	public IResponse<HashMap<String,Object>> loginAction(@Validated AdminUserLoginBo adminUserLoginBo,HttpServletRequest request) {
		//校验图形验证码
        String sysCaptcha = cacheService.get(SecureUtil.md5(adminUserLoginBo.getCaptchaKey()));
        if (!adminUserLoginBo.getCaptcha().toLowerCase().equals(sysCaptcha)) {
            return IResponse.fail("验证码错误");
        }
        if (!IValidateUtils.password(adminUserLoginBo.getPassword())) {
			return IResponse.fail("密码格式错误");
		}
 		String ip = IRequestUtils.getIpAddr(request);
		String userAgent = request.getHeader("User-Agent");
		return IResponse.ok(adminLoginService.login(adminUserLoginBo.getUsername().toLowerCase(), adminUserLoginBo.getPassword(), ip,userAgent));
	}

	@RequestMapping(value = "/logout", method = RequestMethod.POST)
	public IResponse<HashMap<String,Object>> logoutAction(HttpServletRequest request) {
		adminLoginService.logout();
		return IResponse.logout();
	}

	@RequestMapping(value = "/updatePwd", method = RequestMethod.POST)
	public IResponse<HashMap<String,Object>> updatePwdAction(HttpServletRequest request) {
		String oldPwd = IRequestUtils.getString(request,"oldPwd","");
		String pwd = IRequestUtils.getString(request,"pwd","");
		if (!IValidateUtils.password(oldPwd) || !IValidateUtils.password(pwd)) {
			return IResponse.fail("密码格式错误");
		}
		adminLoginService.uodateLoginPwd(oldPwd,pwd);
		return IResponse.logout();
	}
}